<template>
  <div class="account">
    <Loading :loading="loading">

      <Row>
        <div class="titleWrap">
        <h3 class="title">费用类型关联配置</h3>
        <Authc permissions="trade:common:config:settleArgs:edit">
          <Button type="primary" :disabled="addBtn" @click="handleAddRelevance">添加</Button>
        </Authc>
      </div>
      </Row>

      <Table border :columns="columns" :data="dataList">
        <template slot-scope="{ row, index }" slot="type">
          <Select v-model="editType" placeholder="请选择" clearable v-if="editIndex === index">
            <Option v-for="(item, index) in selectCostType" :value="item.key" :key="index">{{ item.value }}</Option>
          </Select>
          <span v-else>{{ row.dataTypeCn }}</span>
        </template>

        <template slot-scope="{ row, index }" slot="payAccount">
          <Input type="text" v-model="editPayAccount" v-if="editIndex === index" maxlength="32" placeholder="请输入，字数不超过32" />
          <span v-else>{{ row.payAcctName }}</span>
        </template>

        <template slot-scope="{ row, index }" slot="payAccountNum">
          <Input type="text" v-model="editPayAccountNum" v-if="editIndex === index" maxlength="32" placeholder="请输入，字数不超过32" />
          <span v-else>{{ row.payAcct }}</span>
        </template>

        <template slot-scope="{ row, index }" slot="receiptAccount">
          <Input type="text" v-model="editReceiptAccount" v-if="editIndex === index" :disabled="editType === 'ME'" maxlength="32" placeholder="请输入，字数不超过32" />
          <span v-else>{{ row.colAcctName }}</span>
        </template>

        <template slot-scope="{ row, index }" slot="receiptAccountNum">
          <Input type="text" v-model="editReceiptAccountNum" v-if="editIndex === index" :disabled="editType === 'ME'" maxlength="32" placeholder="请输入，字数不超过32" />
          <span v-else>{{ row.colAcct }}</span>
        </template>

        <template slot-scope="{ row, index }" slot="action">
          <Authc permissions="trade:common:config:settleArgs:edit">
            <div v-if="editIndex === index">
              <Button @click="handleSave(row,index)">保存</Button>
              <Button @click="handleCancelAddRelevance(row)">取消</Button>
            </div>
            <div v-else>
              <Button :disabled="isAdd" @click="handleDeleteRelevanceConfig(row)">删除</Button>
              <Button :disabled="isAdd" @click="handleTableEdit(row, index)">编辑</Button>
            </div>
          </Authc>
        </template>
      </Table>
    </Loading>
  </div>
</template>
<script>
import config from "@/utils/config";
import { namespace } from "../Module/configAccountModule";
import {
  Input,
  Button,
  Select,
  Form,
  FormItem,
  Option,
  TimePicker,
  Radio,
  RadioGroup,
  Col,
  Row,
  Table,
  Modal,
  Message
} from "view-design";
import Loading from "@/components/Loading";
import Uuid from "uuid";
import Authc from "@/components/Authc";
export default {
  components: {
    Loading,
    Input,
    Button,
    Form,
    FormItem,
    Select,
    Option,
    Authc,
    TimePicker,
    Radio,
    RadioGroup,
    Col,
    Row,
    Table,
    Modal,
    Message
  },
  data: function() {
    let vm = this;
    return {
      taxpayerId: this.$route.params.id,
      formRef: Uuid.v1(),
      formData: {}, /** 对账配置数据 **/
      serverFormData: [], /** 存放从服务器拿到的 对账配置数据，用来取消还原数据 **/
      /** 单选 **/
      radioList: [
        {
          key: '是',
          value: '是'
        },
        {
          key: '否',
          value: '否'
        }
      ],
      /** 轮循次数 **/
      selectAccount: [
        {
          value: '1',
          label: '1次'
        },
        {
          value: '2',
          label: '2次'
        },
        {
          value: '3',
          label: '3次'
        },
        {
          value: '4',
          label: '4次'
        },
        {
          value: '5',
          label: '5次'
        },
        {
          value: '6',
          label: '6次'
        },
        {
          value: '7',
          label: '7次'
        },
        {
          value: '8',
          label: '8次'
        },
        {
          value: '9',
          label: '9次'
        },
        {
          value: '10',
          label: '10次'
        }
      ],
      isAdd: false, /** 点击添加按钮 删除 与 编辑 不可操作 */
      /** 轮询时间间隔 **/
      selectInterval: [
        {
          value: '1',
          label: '1个小时'
        },
        {
          value: '2',
          label: '2个小时'
        },
        {
          value: '3',
          label: '3个小时'
        },
        {
          value: '4',
          label: '4个小时'
        },
        {
          value: '5',
          label: '5个小时'
        },
      ],
      /** 费用类型 **/
      selectCostType: [],
      isDisable: false,
      /** 用来暂存关联配置列表的编辑信息 **/
      editIndex: -1,  /** 当前聚焦的输入框的行数 **/
      editType: '',  /** 费用类型 **/
      editPayAccount: '',  /** 付款银行账户 **/
      editPayAccountNum: '',  /** 付款银行账号 **/
      editReceiptAccount: '',  /** 收款银行账户 **/
      editReceiptAccountNum: '',  /** 收款银行账户 **/
      columns: [
        {
          title: '费用类型',
          align: "center",
          slot: 'type'
        },
        {
          title: '付款银行账户',
          align: "center",
          slot: 'payAccount'
        },
        {
          title: '付款银行账号',
          align: "center",
          slot: 'payAccountNum'
        },
        {
          title: '收款银行账户',
          align: "center",
          slot: 'receiptAccount'
        },
        {
          title: '收款银行账号',
          align: "center",
          slot: 'receiptAccountNum'
        },
        {
          title: '操作',
          slot: 'action'
        }
      ],
      dataList: [],
      addBtn: false /** 新增按钮-禁用 */
    };
  },
  created () {
    this.getTableList();
    this.getConfigSetFun();
    this.getDictionary();
  },
  methods: {
    /** 获取关联列表 **/
    async getTableList () {
      try {
        let res = await  this.$store.dispatch(`${namespace}/getTableList`, {
          payChannel: 'cmb'
        });
        let data = res.data.data;
        this.dataList = data;
      } catch (error) {
        this.$Message.error({
          content: error
        });
      }
    },
    /** 获取配置设置 **/
    async getConfigSetFun(){
      try {

        let res = await this.$store.dispatch(`${namespace}/getConfigSet`, {
          module: 'reconciliation_config'
        });

        this.serverFormData = res.data.data;
        this.renderConfigData(this.serverFormData);

      } catch (error) {
        this.$Message.error({
          content: error
        });
      }
    },
    /** 获取字典 **/
    async getDictionary(){
      try {
        let res = await this.$store.dispatch(`${namespace}/getMerchantSearchKey`);
        this.selectCostType = res.data.data.dataType
      } catch (error) {
        this.$Message.error({
          content: error
        });
      }
    },
    /** 对账配置保存 **/
    async handleSubmit (){
      try {

        let submitData = this.serverFormData.map(item => {
          return {
            id: item.id,
            value: this.formData[item.code]
          }
        });
        await this.$store.dispatch(`${namespace}/saveConfigSet`, submitData);
        this.isDisable = false;
      } catch (error) {
        this.$Message.error({
          content: error
        });
      }
    },
    /** 取消就还原成从服务器拿到的数据 **/
    handleSubmitCancel (type) {
      this.isDisable = false;
      this.renderConfigData(this.serverFormData);
    },
    /** 渲染对账配置设置 **/
    renderConfigData(data){
      data.forEach(item => {
        this.$set(this.formData, `${item.code}_label`, item.name);
        this.$set(this.formData, `${item.code}`, item.value);
      });
    },
    /** 添加 银行账户和账号关联配置 **/
    handleAddRelevance () {
      /** 点击添加的时候先清空一下值，防止用户先点击操作之后没有取消直接点击添加按钮 **/
      this.emptyRelevanceEditData();
      /** 点击添加按钮后 删除- 编辑不可操作 */
      this.isAdd = true;
      /** 禁止添加按钮，只允许添加一条 **/
      this.addBtn = true;
      this.dataList.unshift({
        payChannel: "",  /** 支付渠道 **/
        payAcct: "",   /** 付款银行账户 **/
        payAcctName: "",  /** 付款银行账号 **/
        colAcct: "", /** 收款银行账户 **/
        colAcctName: "",  /** 收款银行账号 **/
      });
      this.editIndex = 0;
    },
    /** 取消添加关联 **/
    handleCancelAddRelevance(row){
      /** 根据 id 判断是否是新增的数据**/
      if(!row.id){
        this.dataList.shift();
      }
      /** 取消之后也需要清空一下值 **/
      this.emptyRelevanceEditData();

      this.editIndex = -1;
      this.isAdd = false; /** 点击添加后， 删除-编辑不可操作 */
      this.addBtn = false; //只允许添加一条
    },
    /** 编辑关联配置 **/
    handleTableEdit (row, index) {
      this.addBtn = true;
      this.editType = row.costType;
      this.editPayAccount = row.payAcctName;
      this.editPayAccountNum = row.payAcct;
      this.editReceiptAccount = row.colAcctName;
      this.editReceiptAccountNum = row.colAcct;
      this.editIndex = index;
    },
    /** 保存关联配置 **/
    async handleSave (row,index) {
      try {
        if( this.editType == '' || this.editPayAccount == '' || this.editPayAccountNum == '') {
          this.$Message.error({
            content: '请完整输入内容'
          });
          return;
        }
        if( this.editType != 'ME' && (this.editReceiptAccount == '' || this.editReceiptAccountNum == '')) {
          this.$Message.error({
            content: '请完整输入内容1'
          });
          return;
        }

        let obj = {
          payChannel: 'cmb',
          costType: this.editType,
          payAcctName: this.editPayAccount,
          payAcct: this.editPayAccountNum,
          colAcctName: this.editReceiptAccount,
          colAcct: this.editReceiptAccountNum,
        }

        let res = null;
        /** 如果有 id 就更新 **/
        if( row.id ){
          obj.id = row.id;

          /** 更新-新增前查询有无相同费用类型 */
          let params = {
            costType: this.editType,
            id: obj.id
          }
          let ress = await this.$store.dispatch(`${namespace}/searchConfigType`, params);
          if (ress.data.ret === 0) {
            if (ress.data.data == '1'){
              this.$Message.warning({
                content: '费用类型不能重复'
              })
              return;
            }
          }

          res = await this.$store.dispatch(`${namespace}/upDataRelevanceConfig`, obj);
          if (res.data.ret === 0) {
            this.$Message.success({
              content: '更新成功'
            })
          }
        } else {

          /** 更新-新增前查询有无相同费用类型 */
          let params = {
            costType: this.editType
          }
          let ress = await this.$store.dispatch(`${namespace}/searchConfigType`, params);
          if (ress.data.ret === 0) {
            if (ress.data.data == '1'){
              this.$Message.warning({
                content: '费用类型不能重复'
              })
              return;
            }
          }

          res = await this.$store.dispatch(`${namespace}/saveRelevanceConfig`, obj);
          if (res.data.ret === 0) {
            this.$Message.success({
              content: '新增成功'
            })
          }
        }
        this.getTableList();
        this.emptyRelevanceEditData();
        this.isAdd = false;
        this.addBtn = false;
        this.editIndex = -1;

      } catch (error) {
        this.$Message.error({
          content: error
        });
      }
    },

    /** 删除关联配置 **/
    handleDeleteRelevanceConfig(row){
      try {
        let id = row.id;
        Modal.confirm({
          render: (h, params) => {
            return h('div', [
              h('div', {
                class: 'selfConfirm'
              }, '确定删除?')
            ]);
          },
          onOk: async () => {
            await this.$store.dispatch(`${namespace}/deleteRelevanceConfig`, id);
            this.getTableList();
          }
        });

      } catch (error) {
        this.$Message.error({
          content: error
        });
      }
    },

    /** 编辑-禁用按钮 */
    handleEdit () {
      this.isDisable = true;
    },
    /** 清空关联编辑数据 **/
    emptyRelevanceEditData(){
      this.editType = '';
      this.editPayAccount ='';
      this.editPayAccountNum ='';
      this.editReceiptAccount ='';
      this.editReceiptAccountNum ='';
    },
  },
  computed: {
    loading: function() {
      let result = this.$store.state[namespace].loading;
      return result;
    }
  }
};
</script>

<style lang="less" scoped>
.account {
  .titleWrap {
    display: flex;
    justify-content: space-between;
    // align-items: center;
    margin-bottom: 10px;
    border-bottom: 1px solid #999;
    padding-bottom: 8px;
  }
  .centerWrap {
    .configBtn {
      text-align: center;
    }

  }
}
.ivu-table-wrapper {
  overflow: inherit;
}
</style>
